package com.yn.pet.util;

import com.yn.common.constant.CacheConstants;
import com.yn.common.constant.Constants;
import com.yn.common.core.redis.RedisCache;
import com.yn.common.utils.StringUtils;
import com.yn.common.utils.spring.SpringUtils;
import com.yn.common.utils.uuid.IdUtils;
import com.yn.pet.entity.AppUser;
import com.yn.pet.entity.model.LoginAppUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class AppTokenUtil {

    private static final int EXPIRE_TIME = 2 * 60 * 60 * 1000;
    private static final String HEADER = "Authorization";
    private static final RedisCache redisCache = SpringUtils.getBean("redisCache");
    private static final String SECRET = "abcdefghijklmnopqrstuvwxyz";
    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;
    private static final ThreadLocal<LoginAppUser> threadLocal = new ThreadLocal<>();

    /**
     * 获取用户身份
     *
     * @param request 请求
     * @return 用户信息
     */
    public static LoginAppUser getLoginAppUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                String userKey = getTokenKey(uuid);
                return redisCache.getCacheObject(userKey);
            } catch (Exception e) {
                log.error("获取用户信息异常'{}'", e.getMessage());
            }
        }
        return null;
    }

    /**
     * 设置用户信息
     *
     * @param loginAppUser 用户信息
     */
    public static void setLoginAppUser(LoginAppUser loginAppUser) {
        if (StringUtils.isNotNull(loginAppUser) && StringUtils.isNotEmpty(loginAppUser.getToken())) {
            refreshToken(loginAppUser);
        }
    }

    /**
     * 删除用户信息
     *
     * @param token 令牌
     */
    public static void delLoginAppUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建token
     *
     * @param appUser 用户信息
     * @return token
     */
    public static String createToken(AppUser appUser) {
        LoginAppUser loginAppUser = new LoginAppUser();
        loginAppUser.setAppUser(appUser);
        loginAppUser.setUserId(appUser.getAppUserId());
        String token = IdUtils.fastUUID();
        loginAppUser.setToken(token);
        refreshToken(loginAppUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    /**
     * 校验 token 有效期小于 20分钟 刷新token
     *
     * @param loginAppUser 用户信息
     */
    public static void verifyToken(LoginAppUser loginAppUser) {
        long expireTime = loginAppUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginAppUser);
        }
    }

    /**
     * 刷新 token
     *
     * @param loginAppUser 用户 信息
     */
    public static void refreshToken(LoginAppUser loginAppUser) {
        loginAppUser.setLoginTime(System.currentTimeMillis());
        loginAppUser.setExpireTime(loginAppUser.getLoginTime() + EXPIRE_TIME);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginAppUser.getToken());
        redisCache.setCacheObject(userKey, loginAppUser, EXPIRE_TIME, TimeUnit.MINUTES);
    }

    public static void putLoginAppUser(LoginAppUser loginAppUser) {
        threadLocal.set(loginAppUser);
    }

    public static void removeLoginAppUser() {
        threadLocal.remove();
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private static String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, SECRET).compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }

    public static AppUser getAppUser() {
        LoginAppUser loginAppUser = threadLocal.get();
        return loginAppUser.getAppUser();
    }

    /**
     * 获取loginAppUser
     * @return LoginAppUser
     */
    public static LoginAppUser getLoginAppUser() {
        return threadLocal.get();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public static String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request 请求
     * @return token
     */
    private static String getToken(HttpServletRequest request) {
        String token = request.getHeader(HEADER);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private static String getTokenKey(String uuid) {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }
}
